﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

using EnterpriseDT.Net.Ftp;

using ComponentFactory.Krypton.Toolkit;

namespace FreeboxHDVideoPlayer
{
    /// <summary>
    /// + temps restant + vitesse + available locally or not
    /// - worker pour checker/download des videos
    /// </summary>
    public partial class MainForm : KryptonForm
    {
        private KryptonManager kryptonManager;
        private const long hddSize = 42949672960;
        private ListVideoWorker listVideoWorker;
        private DeleteVideoWorker deleteVideoWorker;
        private PlayVideoWorker playFTPVideoWorker;
        private DownloadVideosWorker downloadVideosWorker;

        private bool ShowProgress
        {
            set
            {
                if (value)
                {
                    this.loadingCircle.Active = true;
                    this.loadingCircle.Visible = true;
                }
                else
                {
                    this.loadingCircle.Active = false;
                    this.loadingCircle.Visible = false;
                }
                this.labelProgress.Text = "";
            }
        }

        public MainForm()
        {
            InitializeComponent();
            this.components = new System.ComponentModel.Container();
            this.kryptonManager = new KryptonManager(this.components);
            kryptonManager.GlobalPaletteMode = PaletteModeManager.Office2010Black;
            this.ShowProgress = false;
            string host = "hd1.freebox.fr";
            int port = 21;
            string user = "freebox";
            string password = "";
            listVideoWorker = new ListVideoWorker(host, port, user, password);
            listVideoWorker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            listVideoWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(listVideoWorker_RunWorkerCompleted);
            deleteVideoWorker = new DeleteVideoWorker(host, port, user, password);
            deleteVideoWorker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            deleteVideoWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(deleteVideoWorker_RunWorkerCompleted);
            playFTPVideoWorker = new PlayVideoWorker(host, port, user, password);
            playFTPVideoWorker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            playFTPVideoWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(playFTPVideoWorker_RunWorkerCompleted);
            downloadVideosWorker = new DownloadVideosWorker(host, port, user, password);
            downloadVideosWorker.ProgressChanged += new ProgressChangedEventHandler(downloadVideosWorker_ProgressChanged);
            downloadVideosWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(downloadVideosWorker_RunWorkerCompleted);
            VideoLocalCache.Init();
        }

        void downloadVideosWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(this, "Erreur: " + e.Error, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            EnableButtons = true;
        }

        void downloadVideosWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            DownloadVideosWorker.DownloadProgress progress = e.UserState as DownloadVideosWorker.DownloadProgress;
            ListViewItem item = this.listView1.Items[progress.FileName];
            item.SubItems[1].Text = progress.Message;
        }

        void playFTPVideoWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(this, "Erreur: " + e.Error, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            ShowProgress = false;
        }

        void deleteVideoWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(this, "Erreur: " + e.Error, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                if (!listVideoWorker.IsBusy)
                {
                    listVideoWorker.RunWorkerAsync();
                }
            }
            ShowProgress = false;
        }

        void listVideoWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(this, "Erreur: " + e.Error, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                ListVideoWorker.Result result = (ListVideoWorker.Result) e.Result;
                if (result.Size > 0)
                {
                    long allocSizeGo = result.Size;
                    long allocPercentage = (allocSizeGo * 100) / hddSize;
                    this.toolStripProgressBarHDD.Value = (int) allocPercentage;
                    this.toolStripLabelHDD.Text = BytesFormatter.Format(allocSizeGo) 
                        + " / " + BytesFormatter.Format(hddSize);
                }
                this.listView1.BeginUpdate();
                this.listView1.Items.Clear();
                List<Video> videosToDownload = new List<Video>();
                foreach (Video video in result.Videos)
                {
                    string status = "Disponible à distance";
                    bool download = true;
                    if (VideoLocalCache.Exists(video.Name))
                    {
                        if (VideoLocalCache.Size(video.Name) == video.Size)
                        {
                            status = "Disponible en local";
                            download = false;
                        }
                        else
                        {
                            VideoLocalCache.Delete(video.Name);
                        }
                    }
                    if (download)
                    {
                        videosToDownload.Add(video);
                    }
                    ListViewItem item = new ListViewItem(new string[]{video.Name, status});
                    item.Name = video.Name;
                    this.listView1.Items.Add(item);
                }
                this.listView1.EndUpdate();
                if (!this.downloadVideosWorker.IsBusy)
                {
                    //videosToDownload.Clear();
                    this.downloadVideosWorker.RunWorkerAsync(new DownloadVideosWorker.Arg(videosToDownload));
                }
            }
            this.ShowProgress = false;
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.ShowProgress = true;
            this.labelProgress.Text = e.UserState.ToString();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripButtonRefresh_Click(this, EventArgs.Empty);
        }

        private void buttonQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (this.SelectedVideoItem != null)
            {
                if (!this.playFTPVideoWorker.IsBusy)
                {
                    this.playFTPVideoWorker.Video = this.SelectedVideoName;
                    this.playFTPVideoWorker.RunWorkerAsync();
                }
            }
        }

        private ListViewItem SelectedVideoItem
        {
            get
            {
                ListViewItem item = null;
                if (this.listView1.SelectedItems.Count == 1)
                {
                    item = this.listView1.SelectedItems[0];
                }
                return item;
            }
        }

        private string SelectedVideoName
        {
            get
            {
                string name = null;
                if (this.SelectedVideoItem != null)
                {
                    name = this.SelectedVideoItem.Text;
                }
                return name;
            }
        }

        private void toolStripButtonDelete_Click(object sender, EventArgs e)
        {
            if (this.SelectedVideoItem != null)
            {
                string video = this.SelectedVideoName;
                if (DialogResult.Yes == MessageBox.Show(this, "Voulez-vous supprimer " + video + " ?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    if (!this.deleteVideoWorker.IsBusy)
                    {
                        this.deleteVideoWorker.Video = video;
                        this.deleteVideoWorker.RunWorkerAsync();
                    }
                }
            }
        }

        bool EnableButtons
        {
            set
            {
                this.toolStripButtonDelete.Enabled = value;
                this.toolStripButtonRefresh.Enabled = value;
            }
        }

        private void toolStripButtonRefresh_Click(object sender, EventArgs e)
        {
            if (!listVideoWorker.IsBusy)
            {
                EnableButtons = false;
                listVideoWorker.RunWorkerAsync();
            }
        }
    }
}
